package gui.requestDetail;


import gui.ClassroomMenu.exceptions.NoSelection;
import gui.ClassroomMenu.exceptions.NothingSelectedException;

import java.awt.CardLayout;
import java.awt.Color;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import model.basics.Request;
import model.basics.Resource;
import model.search.Order;
import model.time.IllegalTimeValuesException;
import model.time.InvalidMinutesException;
import model.time.NullParametersReceivedExpeption;
import model.time.TimeFrame;

import org.jdesktop.application.Application;

import javax.swing.JButton;
import javax.swing.WindowConstants;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class RequestDetailPanel extends javax.swing.JPanel {
	private static JFrame frame;
	private JPanel orderPanel;
	private JButton nextButton;
	private RequestComparation requestComparation_IL;
	private JScrollPane jScrollPane1;
	private JButton bButton;
	private JTable orderTable;

	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	 * @throws IllegalTimeValuesException 
	 * @throws InvalidMinutesException 
	 * @throws NullParametersReceivedExpeption 
	*/
	public static void main(String[] args) throws NullParametersReceivedExpeption, InvalidMinutesException, IllegalTimeValuesException {
		Main.main();
		frame = new JFrame();
		frame.getContentPane().add(new RequestDetailPanel());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
	
	public RequestDetailPanel() {
		super();
		this.setPreferredSize(new java.awt.Dimension(636, 270));
		initGUI();
	}
	
	private void initGUI() {
		try {
			CardLayout thisLayout = new CardLayout();
			this.setLayout(thisLayout);
			{
				orderPanel = new JPanel();
				this.add(orderPanel, "jPanel1");
				orderPanel.setLayout(null);
				orderPanel.setPreferredSize(new java.awt.Dimension(431, 211));
				{
					jScrollPane1 = new JScrollPane();
					orderPanel.add(jScrollPane1);
					jScrollPane1.setBounds(12, 12, 612, 179);
					{
						orderTable = new JTable();
						jScrollPane1.setViewportView(orderTable);
						TableModel RequestTableModel = new MyTableModel(model.search.System.getAllOrds(), orderTable);
						orderTable.setModel(RequestTableModel);
					}
				}
			}
			{
				requestComparation_IL = new RequestComparation();
				this.add(requestComparation_IL, "jPanel2");
				requestComparation_IL.setPreferredSize(new java.awt.Dimension(389, 213));
				requestComparation_IL.setPanel(this);
			}
			{
				nextButton = new JButton();
				orderPanel.add(nextButton);
				nextButton.setName("nextButton");
				nextButton.setText("->");
				nextButton.setBounds(547, 238, 78, 21);
				nextButton.addActionListener(new NextListener(this));
			}
			{
				bButton = new JButton();
				orderPanel.add(bButton);
				bButton.setBounds(12, 238, 76, 21);
				bButton.setName("bButton");
				bButton.setText("Back");
				bButton.addActionListener(new Back());
			}
			Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class NextListener implements ActionListener{

		private RequestDetailPanel requestPanel;

		public NextListener(RequestDetailPanel requestDetailPanel) {
			this.requestPanel= requestDetailPanel;
		}

		public void actionPerformed(ActionEvent e) {
			try{
				if (!(orderTable.isColumnSelected(0) | orderTable.isColumnSelected(1)) )
					throw new NothingSelectedException();
				else{
			//set values
			requestComparation_IL.setReq(((Order)orderTable.getModel().getValueAt(orderTable.getSelectedRow(),2)).getLastRequest());
			
			Request origReq = ((Order)orderTable.getModel().getValueAt(orderTable.getSelectedRow(),2)).showOriginalRequest(((Order)orderTable.getModel().getValueAt(orderTable.getSelectedRow(),2)).getIdRequest(), model.search.System.getRequestTotalGeneralList());
			requestComparation_IL.setOriginalReq(origReq);
		    
			//generates documents for impresion
			StyledDocument document = generateActualDoc(requestComparation_IL.getReq());
			requestComparation_IL.getReqActualTextPane().setDocument(document);

			StyledDocument document2 = generateOriginalDoc(requestComparation_IL.getReq(),origReq);
			requestComparation_IL.getOriginalReqTextPane().setDocument(document2);
			
			//change panel
			((CardLayout)requestPanel.getLayout()).show(requestPanel,"jPanel2");
				}} catch (NothingSelectedException e1) {
			new NoSelection();
		}
		}
		
		public StyledDocument generateActualDoc(Request req){
			
			StyleContext context = new StyleContext();
		    StyledDocument document = new DefaultStyledDocument(context);
		    Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
		    StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT);
		    StyleConstants.setFontSize(style, 12);
		    StyleConstants.setSpaceAbove(style, 4);
		    StyleConstants.setSpaceBelow(style, 4);
			
			//generate the string for the request info
			String s = 
				"Info of the Request:\n" +
				"    Id: " + req.getId() + "\n"+
				"    Instructor: " + req.getInstructor() +"\n" +
				"    Classroom capacity: " + req.getCapacity() +"\n" +
				"    Resources: \n";
			//resources
			List<String> resString = reqToString(req.getResources(), model.search.System.getAllRes() );
			for (int i = 0; i < resString.size(); i++) {
				s=s+	"                     "+ resString.get(i) + "\n";
			}
			//time frames
			s=s+"    Time: \n";
			TimeFrame tf0 = req.getTimeFrames().get(0);
			TimeFrame tfn = req.getTimeFrames().get(req.getTimeFrames().size()-1);

			s=s+"         Date: ";
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			Date dateStart = tf0.getDateStart().getTime();
			Date dateEnd = tfn.getDateEnd().getTime();
			s=s+ dateFormat.format(dateStart) + " to: " + dateFormat.format(dateEnd) +"\n";
			
			s=s+"         Hour: ";
			SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");
			Date hourStart = tf0.getTimeStart().getTime();
			Date hourEnd = tfn.getTimeEnd().getTime();
			s=s+ hourFormat.format(hourStart) + " to: " + hourFormat.format(hourEnd) +"\n";
			
			s=s+"         Day(s): \n";
			for (int i = 0; i < req.getTimeFrames().size(); i++) {
			s=s+"               "+ req.getTimeFrames().get(i).getDayName() + "\n";
			}
			
			//document of the actual request
			try {
				document.insertString(document.getLength(),s, style);
			} catch (BadLocationException e1) {}
			return document;
		}
		
		public StyledDocument generateOriginalDoc(Request actualR, Request originalR){
			//This methods will generate the document for the first request do ever (according to the selected order)
			
			//making the style
			StyleContext context2 = new StyleContext();
			StyledDocument document2 = new DefaultStyledDocument(context2);
			Style style2 = context2.getStyle(StyleContext.DEFAULT_STYLE);
			StyleConstants.setAlignment(style2, StyleConstants.ALIGN_LEFT);
			StyleConstants.setFontSize(style2, 12);
			StyleConstants.setSpaceAbove(style2, 4);
			StyleConstants.setSpaceBelow(style2, 4);
			
			//document of the original request
			try {
				document2.insertString(document2.getLength(),"Info of the Request:\n" +
						"    Id: " + originalR.getId() + "\n"+
						"    Instructor: " + originalR.getInstructor() +"\n"  , style2);
				
				//prints in red the values that changed
				if(originalR.getCapacity() != actualR.getCapacity()) StyleConstants.setForeground(style2, Color.RED);
				document2.insertString(document2.getLength(),"    Classroom capacity: " + originalR.getCapacity() +"\n" , style2);
				StyleConstants.setForeground(style2, Color.BLACK); //fonts back to black
				
				document2.insertString(document2.getLength(),"    Resources: \n" , style2);
				List<String> ssr = reqToString(originalR.getResources(), model.search.System.getAllRes() );
				List<String> sssr = reqToString(actualR.getResources(), model.search.System.getAllRes() );

				for (int i = 0; i < originalR.getResources().size(); i++) {
					//prints in red the values that changed
					if(! ssr.get(i).equals(sssr.get(i)) ) StyleConstants.setForeground(style2, Color.RED);
					document2.insertString(document2.getLength(),"                     "+ ssr.get(i) + "\n" , style2);
					StyleConstants.setForeground(style2, Color.BLACK); //fonts back to black
				}
				
				//time frames
				document2.insertString(document2.getLength(),"    Time: \n"+"         Date: ",style2);
				TimeFrame actualtf0 = actualR.getTimeFrames().get(0);
				TimeFrame actualtfn = actualR.getTimeFrames().get(actualR.getTimeFrames().size()-1);
				
				TimeFrame originaltf0 = originalR.getTimeFrames().get(0);
				TimeFrame originaltfn = originalR.getTimeFrames().get(originalR.getTimeFrames().size()-1);

				//Date
				SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
				
				Date actualdateStart = actualtf0.getDateStart().getTime();
				Date actualdateEnd = actualtfn.getDateEnd().getTime();

				Date origdateStart = originaltf0.getDateStart().getTime();
				Date origdateEnd = originaltfn.getDateEnd().getTime();
				
				if( !(actualdateStart.equals(origdateStart) | actualdateEnd.equals(origdateEnd) ))StyleConstants.setForeground(style2, Color.RED);
				document2.insertString(document2.getLength(),dateFormat.format(origdateStart) + " to: " + dateFormat.format(origdateEnd) +"\n",style2);
				StyleConstants.setForeground(style2, Color.BLACK); //fonts back to black
				
				//Hour
				document2.insertString(document2.getLength(),"         Hour: ",style2);
				SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm");

				Date actualhourStart = actualtf0.getTimeStart().getTime();
				Date actualhourEnd = actualtfn.getTimeEnd().getTime();

				Date orighourStart = originaltf0.getTimeStart().getTime();
				Date orighourEnd = originaltfn.getTimeEnd().getTime();
				
				if( !(actualhourStart.equals(orighourStart) & actualhourEnd.equals(orighourEnd)) )StyleConstants.setForeground(style2, Color.RED);
				document2.insertString(document2.getLength(),hourFormat.format(orighourStart) + " to: " + hourFormat.format(orighourEnd) +"\n",style2);
				StyleConstants.setForeground(style2, Color.BLACK); //fonts back to black
				
				//Days
				document2.insertString(document2.getLength(),"         Day(s): \n",style2);
				for (int i = 0; i < originalR.getTimeFrames().size(); i++) {
					int j=0;
					boolean b=true;

					while(j < actualR.getTimeFrames().size() & b){
						if( actualR.getTimeFrames().get(j).getDayName().equals(originalR.getTimeFrames().get(i).getDayName())) 
							b=false;
						j++;
					}
					if(b)StyleConstants.setForeground(style2, Color.RED);
					document2.insertString(document2.getLength(),"               "+ originalR.getTimeFrames().get(i).getDayName() + "\n",style2);
					StyleConstants.setForeground(style2, Color.BLACK); //fonts back to black

				}
				
				
				
			
			
			} catch (BadLocationException e1) { }
			return document2;
		}
		

	}

	private List<String> reqToString(HashMap<Resource, Integer> res,
			List<Resource> allRes) {
		// transform the dictionary into a list of strings
		List<String> ssr = new Vector<String>();

		for (int i = 0; i < allRes.size(); i++) {
			if (res.containsKey(allRes.get(i))) {
				String s = allRes.get(i).toString() + ": "
						+ res.get(allRes.get(i)).toString();
				ssr.add(s);
			}
		}
		if (ssr.isEmpty())
			ssr.add("There is no resources");

		return ssr;
	}
	
	public class Back implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			frame.dispose();
		}
		
		
	}
}
